package com.ep.hotfix;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.ep.hotfix.crash.ExceptionCrashHandler;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //打印崩溃信息
        printCrashMessage();
        // 每次启动的时候  去后台获取差分包 fix.apatch  然后修复本地的Bug
        hotFix();


    }

    private void hotFix() {
        // 测试  ， 直接获取本地内存卡里面的 fix.aptach
        File fixFile = new File(Environment.getExternalStorageDirectory(), "fix.apatch");
        if (fixFile.exists()) {
            // 修复Bug
            try {
                // 立马生效不需要重启
                BaseApplication.mPatchManager.addPatch(fixFile.getAbsolutePath());
                Toast.makeText(this, "修复成功", Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "修复失败", Toast.LENGTH_LONG).show();
            }
        }
    }

    public void test(View view){
        Toast.makeText(this,2/1+"test",Toast.LENGTH_LONG).show();
    }




    private void printCrashMessage() {
        // 获取上次的崩溃信息上传到服务器
        File crashFile = ExceptionCrashHandler.getInstance().getCrashFile();
        if (crashFile.exists()) {
        // 正常流程是将崩溃日志上传到服务器，暂时没法做，简单打印下
            try {
                InputStreamReader fileReader = new InputStreamReader(new FileInputStream(crashFile));

                char[] buffer = new char[1024];
                int len = 0;
                while ((len = fileReader.read(buffer))!=-1){
                    String str = new String(buffer,0,len);
                    Log.d("TAG",str);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
